package com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkProcessScheduleInfo;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkProcessScheduleInfoService;
import com.ruicar.afs.cloud.afscase.backtopartnersinfo.entity.CaseBackToPartnersInfo;
import com.ruicar.afs.cloud.afscase.backtopartnersinfo.service.CaseBackToPartnersInfoService;
import com.ruicar.afs.cloud.afscase.cargpsmanage.entity.CarGpsApply;
import com.ruicar.afs.cloud.afscase.cargpsmanage.service.CarGpsApplyService;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelAffiliatedUnits;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelReceivablesAccount;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelAccountInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelAffiliatedUnitsService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.*;
import com.ruicar.afs.cloud.afscase.infomanagement.service.*;
import com.ruicar.afs.cloud.afscase.cargpsmanage.entity.CarGpsDevice;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.CarInsuranceInfo;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.CarInvoiceInfo;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.LoanBankCardInfo;
import com.ruicar.afs.cloud.afscase.cargpsmanage.service.CarGpsDeviceService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.CarInsuranceInfoService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.CarInvoiceInfoService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.LoanBankCardInfoService;
import com.ruicar.afs.cloud.afscase.loangpsruleinfo.entity.LoanGpsRuleInfo;
import com.ruicar.afs.cloud.afscase.loangpsruleinfo.service.LoanGpsRuleInfoService;
import com.ruicar.afs.cloud.afscase.loanmoderuleinfo.entity.LoanModeRuleInfo;
import com.ruicar.afs.cloud.afscase.loanmoderuleinfo.service.LoanModeRuleInfoService;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.PushDataForPos;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.ApproveLoanInfoService;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.vo.CaseContractLogInfo;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinDiscountDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinRentAdjustDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyRentAdjustDetailsService;
import com.ruicar.afs.cloud.bizcommon.dto.rules.atom.AfsRuleInfoDto;
import com.ruicar.afs.cloud.bizcommon.rules.entity.*;
import com.ruicar.afs.cloud.bizcommon.rules.mapper.*;
import com.ruicar.afs.cloud.bizcommon.rules.service.AfsRuleInfoService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.ApproveSubmitInfo;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.*;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.contractdto.*;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.gpsdto.LoanGpsRuleDTO;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.gpsdto.LoanGpsRuleInfoDTO;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.loanmodeldto.LoanModelRuleDto;
import com.ruicar.afs.cloud.common.modules.dto.mq.loan.loanmodeldto.LoanModelRuleInfoDto;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.enums.AttachmentClassEnum;
import com.ruicar.afs.cloud.image.service.ComAttaManageService;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author yk.Li
 * @Date 2020/7/4
 * @description 放款审核MQ组装数据实现类
 */
@Slf4j
@Service
@AllArgsConstructor
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit", name = "enable")
public class ApproveLoanInfoServiceImpl implements ApproveLoanInfoService {
    private final PushDataForPos infoSender;
    private final CaseBackToPartnersInfoService caseBackToPartnersInfoService;
    private final CaseContractInfoService caseContractInfoService;
    private final CaseBaseInfoService caseBaseInfoService;
    private final CaseCustInfoService caseCustInfoService;
    private final CaseCustContactService caseCustContactService;
    private final CaseCustAddressService caseCustAddressService;
    private final CaseCustIndividualService caseCustIndividualService;
    private final CaseCarInfoService caseCarInfoService;
    private final CarInvoiceInfoService carInvoiceInfoService;
    private final CarGpsApplyService carGpsApplyService;
    private final CarInsuranceInfoService carInsuranceInfoService;
    private final CaseCostInfoService caseCostInfoService;
    private final CaseFinancingItemsService caseFinancingItemsService;
    private final ChannelAffiliatedUnitsService affiliatedUnitsService;
    private final LoanBankCardInfoService loanBankCardInfoService;
    private final ChannelAccountInfoService accountInfoService;
    private final CaseChannelInfoService caseChannelInfoService;
    private final ChannelBaseInfoService channelBaseInfoService;
    private final CaseDiscountDetailService caseDiscountDetailService;
    private final WorkProcessScheduleInfoService scheduleInfoService;
    private final CarGpsDeviceService carGpsDeviceService;
    private final ApplyRentAdjustDetailsService rentAdjustDetailsService;
    private final LoanModeRuleInfoService loanModeRuleInfoService;
    private final ComAttachmentFileService comAttachmentFileService;
    private final ComAttaManageService comAttaManageService;
    private LoanGpsRuleInfoService loanGpsRuleInfoService;
    private AfsRuleInfoService afsRuleInfoService;
    private AfsRuleTransExpressMapper afsRuleTransExpressMapper;
    private AfsRuleResultMappingMapper afsRuleResultMappingMapper;
    private AfsRuleItemMapper afsRuleItemMapper;
    private AfsRuleInputMappingMapper afsRuleInputMappingMapper;
    private AfsRuleExpressAtomMapper afsRuleExpressAtomMapper;
    private AfsRuleExpressMapper afsRuleExpressMapper;

    @ApiOperation("退回合作商通知")
    @Override
    public void backToPartnersNotic(String contractNo, String stageId,String taskId) {
        log.info("-----------------退回合作商数据组装begin---------------->");
        Assert.isTrue(StringUtils.isNotBlank(contractNo)&&StringUtils.isNotBlank(stageId)&&StringUtils.isNotBlank(taskId),"退回合作商信息为空！");
        List<CaseBackToPartnersInfo> caseBackToPartnersInfoList = caseBackToPartnersInfoService.list(Wrappers.<CaseBackToPartnersInfo>lambdaQuery()
                .eq(CaseBackToPartnersInfo::getContractNo, contractNo)
                .eq(CaseBackToPartnersInfo::getTaskId,Long.valueOf(taskId)));
        if (CollectionUtils.isNotEmpty(caseBackToPartnersInfoList)) {
            List<BackMsgDto> backMsgDtoList = new ArrayList<>();
            for (CaseBackToPartnersInfo caseBackToPartnersInfo : caseBackToPartnersInfoList) {
                backMsgDtoList.add(BackMsgDto.builder()
                        .fileType(caseBackToPartnersInfo.getFileType())
                        .backDesc(caseBackToPartnersInfo.getBackDesc())
                        .backWords(caseBackToPartnersInfo.getBackWords()).build());
            }
            ArrayList<AttachmentDTO> attachmentDtoList=new ArrayList<>();
            List<ComAttachmentFile> files=comAttachmentFileService.list(Wrappers.<ComAttachmentFile>lambdaQuery()
                    .eq(ComAttachmentFile::getBelongNo,contractNo)
                    .eq(ComAttachmentFile::getBusiNo,contractNo));
            files.forEach(comAttachmentFile -> {
                AttachmentDTO attachmentDTO=new AttachmentDTO();
                log.info("copy====>file==={}=======>{}",comAttachmentFile.getId(),comAttachmentFile.getFileStatus());
                BeanUtil.copyProperties(comAttachmentFile, attachmentDTO, CopyOptions.create().setIgnoreNullValue(true));
                attachmentDtoList.add(attachmentDTO);
            });
            SendToApplyContractInfoDTO sendToApplyContractInfoDTO = SendToApplyContractInfoDTO.builder()
                    .approveType(ApplyStatusEnum.LOAN_RETURN.getState())
                    .backMsgDtoList(backMsgDtoList)
                    .attachmentDtoList(attachmentDtoList)
                    .operateTime(new Date())
                    .stageId(stageId)
                    .taskId(taskId)
                    .contractNo(contractNo).build();
            ApproveSubmitInfo approveSubmitInfo = ApproveSubmitInfo.builder().sendToApplyContractInfoDTO(sendToApplyContractInfoDTO).build();
            log.info("-----------------退回合作商数据组装end---------------->");

            log.info("-----------------退回合作商通知begin---------------->");
            infoSender.sendBackToPartnersNotic(AfsTransEntity.<ApproveSubmitInfo>builder()
                    .transCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_MODIFY_ORDER)
                    .data(approveSubmitInfo).build());
            log.info("-----------------退回合作商通知end---------------->");
        }
    }

    /**
     * @param
     * @description 通知进件合同状态接口数据
     * @author yk.Li
     * @date 2020/7/6
     */
    @ApiOperation("通知进件合同状态")
    @Override
    public void sendToApplyNotic(String contractNo, ApplyStatusEnum statusEnum) {
        log.info("------------通知进件合同状态【" + statusEnum + "】组装begin----------->");
        if (null != contractNo) {
            WorkProcessScheduleInfo scheduleInfo = scheduleInfoService.getOne(Wrappers.<WorkProcessScheduleInfo>lambdaQuery()
                    .eq(WorkProcessScheduleInfo::getContractNo, contractNo), false);
            ArrayList<AttachmentDTO> attachmentDtoList=new ArrayList<>();
            if(statusEnum.equals(ApplyStatusEnum.LOAN_APPROVE_DONE)){
                List<ComAttachmentFile> files=comAttachmentFileService.list(Wrappers.<ComAttachmentFile>lambdaQuery()
                        .eq(ComAttachmentFile::getBelongNo,contractNo)
                        .eq(ComAttachmentFile::getBusiNo,contractNo));
                files.forEach(comAttachmentFile -> {
                    AttachmentDTO attachmentDTO=new AttachmentDTO();
                    BeanUtil.copyProperties(comAttachmentFile, attachmentDTO, CopyOptions.create().setIgnoreNullValue(true));
                    attachmentDtoList.add(attachmentDTO);
                });
            }
            SendToApplyContractInfoDTO sendToApplyContractInfoDTO = SendToApplyContractInfoDTO.builder()
                    .contractNo(contractNo)
                    .attachmentDtoList(attachmentDtoList)
                    .stageId(null != scheduleInfo ? scheduleInfo.getStageId() : "")
                    .approveType(statusEnum.getState())
                    .operateTime(new Date()).build();
            ApproveSubmitInfo approveSubmitInfo = ApproveSubmitInfo.builder().sendToApplyContractInfoDTO(sendToApplyContractInfoDTO).build();
            log.info("-----------------通知进件合同状态【" + statusEnum + "】组装end---------------->");

            log.info("-----------------通知进件合同状态发送begin---------------->");
            infoSender.sendBackToPartnersNotic(AfsTransEntity.<ApproveSubmitInfo>builder()
                    .transCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_MODIFY_ORDER)
                    .data(approveSubmitInfo).build());
            log.info("-----------------通知进件合同状态发送end---------------->");
        }
    }

    /**
     * @param
     * @description 通知进件合同申请状态接口数据
     * @author rongji.zhang
     * @date 2020/9/2
     */
    @ApiOperation("通知进件批量取消申请")
    @Override
    public void sendListToApplyNotic(String applyNoList) {
        log.info("------------通知进件批量取消申请组装begin----------->");
        if (null != applyNoList) {
            ApproveSubmitInfo approveSubmitInfo = ApproveSubmitInfo.builder().applyNoList(applyNoList).build();
            log.info("-----------------通知进件批量取消申请组装end---------------->");

            log.info("-----------------通知进件批量取消申请发送begin---------------->");
            infoSender.sendCancleToPartnersNotic(AfsTransEntity.<ApproveSubmitInfo>builder()
                    .transCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_MODIFY_ORDER)
                    .data(approveSubmitInfo).build());
            log.info("-----------------通知进件批量取消申请发送end---------------->");
        }
    }

    /**
     * @param
     * @Description 通知进件GPS状态接口数据
     * @Author yk.Li
     * @Date 2020/08/07
     */
    @ApiOperation("通知进件GPS状态")
    @Override
    public void sendToApplyNotic(String contractNo, String status) {
        log.info("------------通知进件GPS状态【" + status + "】组装begin----------->");
        if (null != contractNo) {
//            WorkProcessScheduleInfo scheduleInfo = scheduleInfoService.getOne(Wrappers.<WorkProcessScheduleInfo>lambdaQuery()
//                    .eq(WorkProcessScheduleInfo::getContractNo, contractNo), false);
            SendToApplyContractInfoDTO sendToApplyContractInfoDTO = SendToApplyContractInfoDTO.builder()
                    .contractNo(contractNo)
                    .stageId(null)
                    .status(status)
                    .operateTime(new Date()).build();
            ApproveSubmitInfo submitInfo =
                    ApproveSubmitInfo.builder()
                    .sendToApplyContractInfoDTO(sendToApplyContractInfoDTO)
                    .build();
            log.info("-----------------通知进件GPS状态【" + status + "】组装end---------------->");

            log.info("-----------------通知进件GPS状态发送begin---------------->");
            infoSender.sendBackToPartnersNotic(AfsTransEntity.<ApproveSubmitInfo>builder()
                    .transCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_MODIFY_ORDER)
                    .data(submitInfo).build());
            log.info("-----------------通知进件GPS状态发送end---------------->");
        }
    }

    /**
     * @param
     * @return
     * @description 推送接口信息到合同系统
     * @author yk.Li
     * @date 2020/7/8
     */
    @Override
    public void sendLoanMsgToContract(String contractNo) {
        Assert.isTrue(StringUtils.isNotBlank(contractNo), "合同号【" + contractNo + "】不存在，推送数据失败");
        LoanToContractDataMessage loanToContractDataMessage = null;
        try {
            //设定序列化要使用的服务 处理枚举字典不一致的问题
            AfsEnumUtil.setUseService("afs-contract");
            log.info("********************推送合同系统数据组装begin********************》");
            loanToContractDataMessage = addData(contractNo);
            log.info("********************推送合同系统数据组装end********************》");

            infoSender.sendLoanMsgToContract(AfsTransEntity.<LoanToContractDataMessage>builder()
                    .transCode(MqTransCode.AFS_POS_CASE_CONTRACT_CTM_DATA)
                    .data(loanToContractDataMessage).build());
//            log.info(JSON.toJSONString(loanToContractDataMessage));
        } catch (Exception e) {
            log.error("",e);
            throw new AfsBaseException("推送合同系统数据组装失败");
        } finally {
            //清除要设定服务，不清除会导致自己服务出现问题
            AfsEnumUtil.clear();
        }
    }

    /**
     * @param
     * @description 组装接口数据
     * @author yk.Li
     * @date 2020/7/8
     */
    public LoanToContractDataMessage addData(String contractNo) throws Exception {
        ContractMainInfoDTO mainInfo = new ContractMainInfoDTO();
        List<ContractCustPersonalDetailDTO> personalDetail = new ArrayList();
        List<ContractCustBaseInfoDTO> baseInfo = new ArrayList();
        List<ContractContractCustRelationDTO> custRelation = new ArrayList();
        List<ContractCustContactDetailsDTO> custContractDetail = new ArrayList();
        List<ContractCustAddressDetailsDTO> addressDetail = new ArrayList();
        List<ContractCarDetailsDTO> carDetail = new ArrayList();
        List<ContractCarInvoiceDTO> carInvoice = new ArrayList();
        ContractGpsApplyDTO gpsApply = new ContractGpsApplyDTO();
        List<ContractGpsDeviceDTO> gpsDevice = new ArrayList();
        List<ContractInsuranceInfoDTO> insuranceInfo = new ArrayList();
        List<ContractFinancialAgreementDTO> fnancialAgreement = new ArrayList();
        List<ContractFinancingItemsDTO> financingItems = new ArrayList();
        ContractAffiliatedUnitDTO affiliatedUnit = new ContractAffiliatedUnitDTO();
        ContractBankCardDTO bankCard = new ContractBankCardDTO();
        List<ContractChannelInfoDTO> channelInfo = new ArrayList();
        List<ContractDiscountDetailsDTO> discountDetails = new ArrayList();
        List<ContractCustContactsDTO> bsicCustContacts = new ArrayList<>();
        List<ContractFinRentAdjustDetailsDTO> finRentAdjustDetailsDTOList= new ArrayList<>();


        log.info("====================合同主信息=======================》");
        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getContractNo, contractNo));
        if (null == caseContractInfo) {
            throw new Exception("合同号【" + contractNo + "】主信息不存在");
        }
        BeanUtils.copyProperties(caseContractInfo, mainInfo);
        if (StringUtils.isBlank(mainInfo.getApplyNo())) {
            throw new Exception("合同编号【" + contractNo + "】->申请编号不存在");
        }
        mainInfo.setBusinessType((BusinessTypeEnum) AfsEnumUtil.getEnum(caseContractInfo.getBusinessType(), BusinessTypeEnum.class));
        mainInfo.setContractStatus(caseContractInfo.getContractStatus());
        mainInfo.setLendingMode((LoanModelEnum) AfsEnumUtil.getEnum(caseContractInfo.getLendingMode(), LoanModelEnum.class));

        CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>lambdaQuery().eq(CaseBaseInfo::getApplyNo, mainInfo.getApplyNo()));
        mainInfo.setIntoFirstDate(caseBaseInfo.getPassFirstDate());
        mainInfo.setCarNature((CarNatureEnum) AfsEnumUtil.getEnum(caseBaseInfo.getCarNature(), CarNatureEnum.class));
        mainInfo.setProductId(caseBaseInfo.getProductId());
        mainInfo.setProductName(caseBaseInfo.getProductName());

        List<CaseCustInfo> caseCustInfoList = caseCustInfoService.list(Wrappers.<CaseCustInfo>lambdaQuery()
                .eq(StringUtils.isNotBlank(mainInfo.getApplyNo()), CaseCustInfo::getApplyNo, mainInfo.getApplyNo()));
        if (null != caseCustInfoList) {
            log.info("========合同客户基本信息-合同与用户角色关系信息==========》");
            for (CaseCustInfo caseCustInfo : caseCustInfoList) {
                //合同客户基本信息
                ContractCustBaseInfoDTO contractCustBaseInfoDTO = new ContractCustBaseInfoDTO();
                BeanUtils.copyProperties(caseCustInfo, contractCustBaseInfoDTO);
                contractCustBaseInfoDTO.setContractNo(contractNo);
                contractCustBaseInfoDTO.setCustType((CustTypeEnum) AfsEnumUtil.getEnum(caseCustInfo.getCustType(), CustTypeEnum.class));
                contractCustBaseInfoDTO.setIsLongTerm((WhetherEnum) AfsEnumUtil.getEnum(caseCustInfo.getIsLongTerm(), WhetherEnum.class));
                contractCustBaseInfoDTO.setCustRole((CustRoleEnum) AfsEnumUtil.getEnum(caseCustInfo.getCustRole(), CustRoleEnum.class));
                baseInfo.add(contractCustBaseInfoDTO);

                //合同与用户角色关系信息
                ContractContractCustRelationDTO contractContractCustRelationDTO = new ContractContractCustRelationDTO();
                BeanUtils.copyProperties(caseCustInfo, contractContractCustRelationDTO);
                contractContractCustRelationDTO.setId(caseCustInfo.getId());
                contractContractCustRelationDTO.setContractNo(contractNo);
                contractContractCustRelationDTO.setCustRole((CustRoleEnum) AfsEnumUtil.getEnum(caseCustInfo.getCustRole(), CustRoleEnum.class));
                custRelation.add(contractContractCustRelationDTO);

                /**组装联系方式*/
                if(!ObjectUtils.isEmpty(caseCustInfo.getTelPhone())){
                    ContractCustContactDetailsDTO custContact=new ContractCustContactDetailsDTO();
                    custContact.setId(caseCustInfo.getId());
                    custContact.setContactNumber(caseCustInfo.getTelPhone());
                    custContact.setContactType(ContactTypeEnum.PHONE);
                    custContractDetail.add(custContact);
                }
            }
        }
        ContractCustBaseInfoDTO ContactBaseInfoDTO=new ContractCustBaseInfoDTO();
        if (CollectionUtils.isNotEmpty(baseInfo)) {
            for (ContractCustBaseInfoDTO contractCustBaseInfoDTO : baseInfo) {
                CaseCustIndividual caseCustIndividual = caseCustIndividualService.getOne(Wrappers.<CaseCustIndividual>lambdaQuery()
                        .eq(CaseCustIndividual::getCustId, contractCustBaseInfoDTO.getId()));
                if (null != caseCustIndividual) {
                    log.info("========合同个人客户【" + contractCustBaseInfoDTO.getId() + "】明细信息==========》");
                    ContractCustPersonalDetailDTO custPersonalDetailDTO = new ContractCustPersonalDetailDTO();
                    BeanUtils.copyProperties(caseCustIndividual, custPersonalDetailDTO);
                    custPersonalDetailDTO.setSex((SexEnum) AfsEnumUtil.getEnum(caseCustIndividual.getSex(), SexEnum.class));
                    custPersonalDetailDTO.setUnclearedLoan(Convert.toBigDecimal(caseCustIndividual.getOutstandingLoan(), BigDecimal.ZERO));
                    personalDetail.add(custPersonalDetailDTO);
                }

                List<CaseCustAddress> custAddressList = caseCustAddressService.list(Wrappers.<CaseCustAddress>lambdaQuery()
                        .eq(CaseCustAddress::getCustId, contractCustBaseInfoDTO.getId()));
                if (CollectionUtils.isNotEmpty(custAddressList)) {
                    log.info("=======合同客户【" + contractCustBaseInfoDTO.getId() + "】地址=============》");
                    for (CaseCustAddress custAddress : custAddressList) {
                        ContractCustAddressDetailsDTO contractCustAddressDetailsDTO = new ContractCustAddressDetailsDTO();
                        BeanUtils.copyProperties(custAddress, contractCustAddressDetailsDTO);
                        contractCustAddressDetailsDTO.setAddressType((AddressTypeEnum) AfsEnumUtil.getEnum(custAddress.getAddressType(), AddressTypeEnum.class));
                        contractCustAddressDetailsDTO.setValidStatus((ValidStatusEnum) AfsEnumUtil.getEnum(custAddress.getValidStatus(), ValidStatusEnum.class));
                        contractCustAddressDetailsDTO.setIsDefault((WhetherEnum) AfsEnumUtil.getEnum(custAddress.getIsDefault(), WhetherEnum.class));
                        addressDetail.add(contractCustAddressDetailsDTO);
                    }
                }

                /**组装联系方式*/
                if(!ObjectUtils.isEmpty(caseCustIndividual.getUnitTelPhone())){
                    ContractCustContactDetailsDTO custContact=new ContractCustContactDetailsDTO();
                    custContact.setId(caseCustIndividual.getCustId());
                    custContact.setContactNumber(caseCustIndividual.getUnitTelPhone());
                    custContact.setContactType(ContactTypeEnum.WORK_PHONE);
                    custContractDetail.add(custContact);
                }

                log.info("========合同客户联系人信息==========》");
                List<CaseCustContact> caseCustContactList = caseCustContactService.list(Wrappers.<CaseCustContact>lambdaQuery()
                        .eq(CaseCustContact::getCustId, contractCustBaseInfoDTO.getId().toString()));
                if (CollectionUtils.isNotEmpty(caseCustContactList)) {
                    for (CaseCustContact caseCustContact : caseCustContactList) {
                        log.info("========合同客户联系人【" + caseCustContact.getId() + "】==========》");
                        ContractCustContactsDTO contractCustContactsDTO = new ContractCustContactsDTO();
                        BeanUtils.copyProperties(caseCustContact, contractCustContactsDTO);
                        contractCustContactsDTO.setContractNo(contractNo);
                        bsicCustContacts.add(contractCustContactsDTO);

                        /**如果是夫妻关系，添加客户信息主表为联系人*/
                        if(CustRelationEnum.COUPLE.getCode().equals(caseCustContact.getCustRelation())){
                            ContactBaseInfoDTO.setId(caseCustContact.getId());
                            ContactBaseInfoDTO.setCertNo(caseCustContact.getCertNo());
                            ContactBaseInfoDTO.setCertType(caseCustContact.getCertType());
                            ContactBaseInfoDTO.setContractNo(contractNo);
                            ContactBaseInfoDTO.setCustName(caseCustContact.getCustName());
                            ContactBaseInfoDTO.setCustRole(CustRoleEnum.CONTACT);
                            ContactBaseInfoDTO.setTelPhone(caseCustContact.getTelPhone());
                            ContactBaseInfoDTO.setCustType(CustTypeEnum.PERSON);
                            //合同与用户角色关系信息
                            ContractContractCustRelationDTO contractContractCustRelationDTO = new ContractContractCustRelationDTO();
                            contractContractCustRelationDTO.setId(caseCustContact.getId());
                            contractContractCustRelationDTO.setContractNo(contractNo);
                            contractContractCustRelationDTO.setCustRole(CustRoleEnum.CONTACT);
                            contractContractCustRelationDTO.setCustRelation(CustRelationEnum.COUPLE.getCode());
                            custRelation.add(contractContractCustRelationDTO);
                            /***/
                            ContractCustContactDetailsDTO custContact=new ContractCustContactDetailsDTO();
                            custContact.setId(caseCustContact.getId());
                            custContact.setContactNumber(caseCustContact.getTelPhone());
                            custContact.setContactType(ContactTypeEnum.PHONE);
                            custContractDetail.add(custContact);

                            ContractCustAddressDetailsDTO contractCustAddressDetailsDTO = new ContractCustAddressDetailsDTO();
                            contractCustAddressDetailsDTO.setCustId(caseCustContact.getId());
                            contractCustAddressDetailsDTO.setAddressType(AddressTypeEnum.LIVING);
                            contractCustAddressDetailsDTO.setProvince(caseCustContact.getLivingProvince());
                            contractCustAddressDetailsDTO.setCity(caseCustContact.getLivingCity());
                            contractCustAddressDetailsDTO.setCounty(caseCustContact.getLivingCounty());
                            contractCustAddressDetailsDTO.setStreet(caseCustContact.getLivingStreet());
                            contractCustAddressDetailsDTO.setDetailAddress(caseCustContact.getDetailAddress());
                            contractCustAddressDetailsDTO.setValidStatus(ValidStatusEnum.EFFECTIVE);
                            addressDetail.add(contractCustAddressDetailsDTO);
                        }
                    }
                }
            }
        }
        if(!ObjectUtils.isEmpty(ContactBaseInfoDTO.getId())){
            baseInfo.add(ContactBaseInfoDTO);
        }
        List<CaseCarInfo> caseCarInfoList = caseCarInfoService
                .list(Wrappers.<CaseCarInfo>lambdaQuery().eq(CaseCarInfo::getContractNo, contractNo));
        if (CollectionUtils.isNotEmpty(caseCarInfoList)) {
            log.info("===============车辆申请信息===============》");
            for (CaseCarInfo caseCarInfo : caseCarInfoList) {
                ContractCarDetailsDTO contractCarDetailsDTO = new ContractCarDetailsDTO();
                BeanUtils.copyProperties(caseCarInfo, contractCarDetailsDTO);
                contractCarDetailsDTO.setCarFunction((CarFunctionEnum) AfsEnumUtil.getEnum(caseCarInfo.getCarFunction(), CarFunctionEnum.class));
                contractCarDetailsDTO.setIsCirTrans((WhetherEnum) AfsEnumUtil.getEnum(caseCarInfo.getIsCirTrans(), WhetherEnum.class));
                contractCarDetailsDTO.setIsMortgage((WhetherEnum) AfsEnumUtil.getEnum(caseCarInfo.getIsMortgage(), WhetherEnum.class));
                contractCarDetailsDTO.setDealerName(StringUtil.isNotEmpty(caseCarInfo.getCarDealerName()) ? caseCarInfo.getCarDealerName() : "");
                carDetail.add(contractCarDetailsDTO);

                CarInvoiceInfo carInvoiceInfo = carInvoiceInfoService
                        .getOne(Wrappers.<CarInvoiceInfo>lambdaQuery().eq(CarInvoiceInfo::getCarId, caseCarInfo.getId()));
                if (null != carInvoiceInfo) {
                    log.info("========发票信息表carID【" + caseCarInfo.getId() + "】===========》");
                    ContractCarInvoiceDTO contractCarInvoiceDTO = new ContractCarInvoiceDTO();
                    BeanUtils.copyProperties(carInvoiceInfo, contractCarInvoiceDTO);
                    carInvoice.add(contractCarInvoiceDTO);
                }

                CarGpsApply carGpsApply = carGpsApplyService
                        .getOne(Wrappers.<CarGpsApply>lambdaQuery().eq(CarGpsApply::getContractNo, contractNo));
                log.info("====================GPS申请信息====================》");
                if (null != carGpsApply) {
                    BeanUtils.copyProperties(carGpsApply, gpsApply);
                    gpsApply.setIsRobberyBag((WhetherEnum) AfsEnumUtil.getEnum(carGpsApply.getIsRobberyBag(), WhetherEnum.class));
                }

                List<CarGpsDevice> carGpsDeviceList = carGpsDeviceService
                        .list(Wrappers.<CarGpsDevice>lambdaQuery().eq(CarGpsDevice::getCarId, caseCarInfo.getId()));
                if (CollectionUtils.isNotEmpty(carGpsDeviceList)) {
                    log.info("===========GPS设备信息关联carID【" + caseCarInfo.getId() + "】============》");
                    for (CarGpsDevice carGpsDevice : carGpsDeviceList) {
                        ContractGpsDeviceDTO contractGpsDeviceDTO = new ContractGpsDeviceDTO();
                        BeanUtils.copyProperties(carGpsDevice, contractGpsDeviceDTO);
                        contractGpsDeviceDTO.setCarVin(caseCarInfo.getCarVin());
                        gpsDevice.add(contractGpsDeviceDTO);
                    }
                }

                List<CarInsuranceInfo> carInsuranceInfoList = carInsuranceInfoService
                        .list(Wrappers.<CarInsuranceInfo>lambdaQuery().eq(CarInsuranceInfo::getCarId, caseCarInfo.getId()));
                if (CollectionUtils.isNotEmpty(carInsuranceInfoList)) {
                    log.info("===========保险信息carID【" + caseCarInfo.getId() + "】===========》");
                    for (CarInsuranceInfo carInsuranceInfo : carInsuranceInfoList) {
                        ContractInsuranceInfoDTO contractInsuranceInfoDTO = new ContractInsuranceInfoDTO();
                        BeanUtils.copyProperties(carInsuranceInfo, contractInsuranceInfoDTO);
                        contractInsuranceInfoDTO.setInsuranceType((InsuranceTypeEnum) AfsEnumUtil.getEnum(carInsuranceInfo.getInsuranceType(), InsuranceTypeEnum.class));
                        insuranceInfo.add(contractInsuranceInfoDTO);
                    }
                }
                if(!ObjectUtils.isEmpty(caseCarInfo)){
                    if(caseBaseInfo.getAffiliatedWay().equals(AffiliatedWayEnum.PERSONAL_AFFILIATED.getCode())){
                        affiliatedUnit.setAffiliatedName(caseCarInfo.getIndBusinessName());
                        affiliatedUnit.setSocUniCrtCode(caseCarInfo.getIndBusinessUsci());
                    }
                    if(caseBaseInfo.getAffiliatedWay().equals(AffiliatedWayEnum.COMPANY_AFFILIATED.getCode())
                            ||caseBaseInfo.getAffiliatedWay().equals(AffiliatedWayEnum.NETWORK_CAR_AFFILIATED.getCode())){
                        ChannelAffiliatedUnits channelAffiliatedUnits = affiliatedUnitsService
                                .getOne(Wrappers.<ChannelAffiliatedUnits>lambdaQuery().eq(ChannelAffiliatedUnits::getId, Long.parseLong(caseCarInfo.getAffCompanyId())));
                        if (null != channelAffiliatedUnits) {
                            log.info("====================挂靠单位carID【" + caseCarInfo.getId() + "】====================》");
                            BeanUtils.copyProperties(channelAffiliatedUnits, affiliatedUnit);
                        }
                    }
                    affiliatedUnit.setContractNo(contractNo);
                    affiliatedUnit.setCarId(caseCarInfo.getId());
                    affiliatedUnit.setCooperPlat(caseCarInfo.getCooperPlat());
                    affiliatedUnit.setAffiliatedType((AffiliatedWayEnum) AfsEnumUtil.getEnum(caseBaseInfo.getAffiliatedWay(), AffiliatedWayEnum.class));
                }else{
                    throw new Exception("合同编号【" + contractNo + "】->车辆信息不存在");
                }
            }
        }else{
            throw new Exception("合同编号【" + contractNo + "】->车辆信息不存在");
        }

        List<FinCostDetails> FinCostDetailsList = caseCostInfoService
                .list(Wrappers.<FinCostDetails>lambdaQuery().eq(FinCostDetails::getApplyNo, mainInfo.getApplyNo()));
        if (CollectionUtils.isNotEmpty(FinCostDetailsList)) {
            log.info("====================金融协议====================》");
            for (FinCostDetails costInfo : FinCostDetailsList) {
                ContractFinancialAgreementDTO financialAgreementDTO = new ContractFinancialAgreementDTO();
                BeanUtils.copyProperties(costInfo, financialAgreementDTO);
                financialAgreementDTO.setDiscountType((AfsEnumUtil.getEnum(costInfo.getDiscountType(), DiscountTypeEnum.class)).toString());
                financialAgreementDTO.setContractNo(contractNo);
                financialAgreementDTO.setCostType((CostTypeEnum) AfsEnumUtil.getEnum(costInfo.getCostType(), CostTypeEnum.class));
                fnancialAgreement.add(financialAgreementDTO);

                List<FinDiscountDetails> discountDetailList = caseDiscountDetailService
                        .list(Wrappers.<FinDiscountDetails>lambdaQuery().eq(null != costInfo, FinDiscountDetails::getCostId, costInfo.getId()));
                if (CollectionUtils.isNotEmpty(discountDetailList)) {
                    log.info("===========合同贴息明细信息关联costID【" + costInfo.getId() + "】==========》");
                    for (FinDiscountDetails caseDiscountDetail : discountDetailList) {
                        ContractDiscountDetailsDTO discountDetailsDTO = new ContractDiscountDetailsDTO();
                        BeanUtils.copyProperties(caseDiscountDetail, discountDetailsDTO);
                        discountDetailsDTO.setContractNo(contractNo);
                        discountDetailsDTO.setCostType((CostTypeEnum) AfsEnumUtil.getEnum(costInfo.getCostType(), CostTypeEnum.class));
                        discountDetails.add(discountDetailsDTO);
                    }
                }
            }
        }

        List<FinFinancingItems> financingItemsList = caseFinancingItemsService
                .list(Wrappers.<FinFinancingItems>lambdaQuery().eq(FinFinancingItems::getApplyNo, mainInfo.getApplyNo()));
        if (null != financingItemsList) {
            log.info("====================合同融资项目表====================》");
            for (FinFinancingItems finFinancingItems : financingItemsList) {
                ContractFinancingItemsDTO contractFinancingItemsDTO = new ContractFinancingItemsDTO();
                contractFinancingItemsDTO.setContractNo(contractNo);
                BeanUtils.copyProperties(finFinancingItems, contractFinancingItemsDTO);
                //二期使用 contractFinancingItemsDTO.setIsCalLoanAmt();
                financingItems.add(contractFinancingItemsDTO);
            }
        }

        List<FinRentAdjustDetails> finRentAdjustDetailsList = rentAdjustDetailsService
                .list(Wrappers.<FinRentAdjustDetails>lambdaQuery().eq(FinRentAdjustDetails::getApplyNo, mainInfo.getApplyNo()));
        if (CollectionUtil.isNotEmpty(finRentAdjustDetailsList)) {
            log.info("====================合同租金调整表====================》");
            for (FinRentAdjustDetails finRentAdjustDetails : finRentAdjustDetailsList) {
                ContractFinRentAdjustDetailsDTO contractFinRentAdjustDetailsDTO = new ContractFinRentAdjustDetailsDTO();
                contractFinRentAdjustDetailsDTO.setContractNo(contractNo);
                BeanUtils.copyProperties(finRentAdjustDetails, contractFinRentAdjustDetailsDTO);
                finRentAdjustDetailsDTOList.add(contractFinRentAdjustDetailsDTO);
            }
        }

        LoanBankCardInfo loanBankCardInfo = loanBankCardInfoService
                .getOne(Wrappers.<LoanBankCardInfo>lambdaQuery().eq(LoanBankCardInfo::getContractNo, contractNo));
        if (null != loanBankCardInfo) {
            log.info("====================合同银行卡信息====================》");
            BeanUtils.copyProperties(loanBankCardInfo, bankCard);
            bankCard.setAuthorizeWay((AuthorizeWayEnum) AfsEnumUtil.getEnum(loanBankCardInfo.getAuthorizeWay(), AuthorizeWayEnum.class));
            /**银行卡激活默认签约成功*/
            bankCard.setVerStatus(VerStatusEnum.alreadySign);
        }

        CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                .eq(CaseChannelInfo::getApplyNo, mainInfo.getApplyNo()));
        if (null != caseChannelInfo) {
            ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>lambdaQuery()
                    .eq(StringUtils.isNotBlank(caseChannelInfo.getDealerNo()), ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()));
            if (null != channelBaseInfo) {
                log.info("====================合同渠道信息记录信息====================》");
                mainInfo.setChannelType((ChannelTypeEnum) AfsEnumUtil.getEnum(channelBaseInfo.getChannelType(), ChannelTypeEnum.class));
                mainInfo.setChannelName(channelBaseInfo.getChannelFullName());
                //String id = AfsEnumUtil.key(PaymentObjectEnum.partners).equals(channelBaseInfo.getPaymentObject())?channelBaseInfo.getChannelId():caseChannelInfo.get;
                mainInfo.setChannelId(channelBaseInfo.getId());
                /**直营车商的案件从渠道案件表获取直营车商ID可在渠道付款账户表查询付款账户信息*/
                List<ChannelReceivablesAccount> account=new ArrayList<>();
                //0-主体，1-车商
                if(AfsEnumUtil.key(PaymentObjectEnum.partners).equals(channelBaseInfo.getPaymentObject())){
                    account = accountInfoService.list(Wrappers.<ChannelReceivablesAccount>query().lambda()
                            .eq(ChannelReceivablesAccount::getChannelId, channelBaseInfo.getId())
                            .eq(ChannelReceivablesAccount::getStatus,ChannelOnlineEnum.ENABLE.getCode()));
                }else if(AfsEnumUtil.key(PaymentObjectEnum.car_dealer).equals(channelBaseInfo.getPaymentObject())){
                    account = accountInfoService.list(Wrappers.<ChannelReceivablesAccount>query().lambda()
                            .eq(ChannelReceivablesAccount::getChannelId, Long.valueOf(caseChannelInfo.getCarDealersId()))
                            .eq(ChannelReceivablesAccount::getStatus,ChannelOnlineEnum.ENABLE.getCode()));
                }
                Assert.isTrue(CollectionUtils.isNotEmpty(account), "合同号【" + contractNo + "】渠道ID【"+channelBaseInfo.getId()+"】=>付款账户信息为空：");
                log.info("====================合同渠道账户信息记录信息====================》");
                for (ChannelReceivablesAccount channelReceivablesAccount : account) {
                    ContractChannelInfoDTO contractChannelInfoDTO = new ContractChannelInfoDTO();
                    BeanUtils.copyProperties(channelReceivablesAccount, contractChannelInfoDTO);
                    contractChannelInfoDTO.setCollectionType((AfsEnumUtil.getEnum(channelReceivablesAccount.getCollectionType(), CollectionTypeEnum.class)).toString());
                    contractChannelInfoDTO.setContractNo(contractNo);
                    contractChannelInfoDTO.setContactName(channelBaseInfo.getChannelAdmin());
                    contractChannelInfoDTO.setContactPhone(channelBaseInfo.getChannelAdminTel());
                    contractChannelInfoDTO.setChannelType(mainInfo.getChannelType());
                    contractChannelInfoDTO.setSocUniCrtCode(channelBaseInfo.getSocUniCrtCode());
                    contractChannelInfoDTO.setPartnerCode(channelBaseInfo.getChannelCode());
                    contractChannelInfoDTO.setChannelFullName(channelBaseInfo.getChannelFullName());
                    contractChannelInfoDTO.setAccountType((CustTypeEnum) AfsEnumUtil.getEnum(channelReceivablesAccount.getAccountType(), CustTypeEnum.class));
                    contractChannelInfoDTO.setOnlineDate(channelBaseInfo.getOnlineDate());
                    contractChannelInfoDTO.setRegistrationDate(channelBaseInfo.getRegistrationDate());
                    contractChannelInfoDTO.setLegalPerson(channelBaseInfo.getLegalPerson());
                    contractChannelInfoDTO.setLegalPersonIdCard(channelBaseInfo.getLegalPersonIdCard());
                    contractChannelInfoDTO.setChannelAdminMail(channelBaseInfo.getChannelAdminMail());
                    contractChannelInfoDTO.setChannelAdminProvince(channelBaseInfo.getChannelAdminProvince());
                    contractChannelInfoDTO.setChannelAdminCity(channelBaseInfo.getChannelAdminCity());
                    contractChannelInfoDTO.setChannelAdminAddress(channelBaseInfo.getChannelAdminAddress());
                    contractChannelInfoDTO.setChannelProvince(channelBaseInfo.getChannelProvince());
                    contractChannelInfoDTO.setChannelCity(channelBaseInfo.getChannelCity());
                    contractChannelInfoDTO.setAccountAttribute((BusinessTypeEnum)AfsEnumUtil.getEnum(channelReceivablesAccount.getAccountAttribute(),BusinessTypeEnum.class));
                    contractChannelInfoDTO.setChannelBelong(channelBaseInfo.getChannelBelong());
                    channelInfo.add(contractChannelInfoDTO);
                }
            }
        }
        log.info("====================合同信息组装完成====================》");
        return LoanToContractDataMessage.builder()
                .mainInfo(mainInfo)
                .baseInfo(baseInfo)
                .custContractDetail(custContractDetail)
                .addressDetail(addressDetail)
                .custRelation(custRelation)
                .personalDetail(personalDetail)
                .carDetail(carDetail)
                .carInvoice(carInvoice)
                .insuranceInfo(insuranceInfo)
                .gpsApply(gpsApply)
                .gpsDevice(gpsDevice)
                .fnancialAgreement(fnancialAgreement)
                .financingItems(financingItems)
                .affiliatedUnit(affiliatedUnit)
                .discountDetails(discountDetails)
                .bankCard(bankCard)
                .channelInfo(channelInfo)
                .bsicCustContacts(bsicCustContacts)
                .finRentAdjustDetailsList(finRentAdjustDetailsDTOList)
                .build();
    }

    @ApiOperation("放款数据落库结果通知")
    @Override
    public void loanApplyResult(CaseContractLogInfo logInfo) {
        AfsTransEntity<LoanSubmitInfo> transEntity = new AfsTransEntity();
        LoanSubmitInfo loanSubmitInfo = new LoanSubmitInfo();
        LoanResultInfoDto loanResultInfoDto = this.getLoanResult(logInfo);
        loanSubmitInfo.setLoanResultInfoDto(loanResultInfoDto);
        transEntity.setTransCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_MODIFY_LOAN);
        transEntity.setData(loanSubmitInfo);
        infoSender.loanApplyResult(transEntity);
    }


    /**
     * 进件数据落库结果通知
     */
    private LoanResultInfoDto getLoanResult(CaseContractLogInfo logInfo) {
        LoanResultInfoDto loaResultInfoDto = new LoanResultInfoDto();
        // 申请编号
        loaResultInfoDto.setApplyNo(logInfo.getApplyNo());
        // 合同号码
        loaResultInfoDto.setContractNo(logInfo.getContractNo());
        // 返回结果
        loaResultInfoDto.setResult(logInfo.getResult());
        return loaResultInfoDto;
    }

    @ApiOperation("GPS安装规则数据推送")
    @Override
    public void sendGpsMsgToApply(Long id) {
        log.info("-----------------GPS安装规则数据组装begin---------------->");

        Assert.isTrue(null != id, "规则【" + id + "】不存在，推送数据失败");

        LoanGpsRuleInfo loanGpsRuleInfo = loanGpsRuleInfoService.getById(id);
        LoanGpsRuleInfoDTO loanGpsRuleInfoDTO = new LoanGpsRuleInfoDTO();
        BeanUtils.copyProperties(loanGpsRuleInfo, loanGpsRuleInfoDTO);

        Long ruleId = loanGpsRuleInfo.getRuleId();
        Assert.isTrue(null != ruleId, "规则【" + id + "】规则编号不存在，推送数据失败");

        AfsRuleInfo afsRuleInfo = afsRuleInfoService.getById(ruleId);
        AfsRuleInfoDto afsRuleInfoDto = new AfsRuleInfoDto();
        BeanUtils.copyProperties(afsRuleInfo, afsRuleInfoDto);

        List<AfsRuleTransExpress> afsRuleTransExpressList = afsRuleTransExpressMapper
                .selectList(Wrappers.<AfsRuleTransExpress>lambdaQuery().eq(AfsRuleTransExpress::getRuleId, ruleId));

        AfsRuleResultMapping afsRuleResultMapping = afsRuleResultMappingMapper
                .selectOne(Wrappers.<AfsRuleResultMapping>lambdaQuery().eq(AfsRuleResultMapping::getRuleId, ruleId));

        List<AfsRuleItem> afsRuleItemList = afsRuleItemMapper
                .selectList(Wrappers.<AfsRuleItem>lambdaQuery().eq(AfsRuleItem::getRuleId, ruleId));

        List<AfsRuleInputMapping> afsRuleInputMappingList = afsRuleInputMappingMapper
                .selectList(Wrappers.<AfsRuleInputMapping>lambdaQuery().eq(AfsRuleInputMapping::getRuleId, ruleId));

        List<AfsRuleExpressAtom> afsRuleExpressAtomList = afsRuleExpressAtomMapper
                .selectList(Wrappers.<AfsRuleExpressAtom>lambdaQuery().eq(AfsRuleExpressAtom::getRuleId, ruleId));

        List<AfsRuleExpress> afsRuleExpressList = afsRuleExpressMapper
                .selectList(Wrappers.<AfsRuleExpress>lambdaQuery().eq(AfsRuleExpress::getRuleId, ruleId));
        LoanGpsRuleDTO loanGpsRuleDTO = LoanGpsRuleDTO.builder()
                .loanGpsRuleInfoDTO(loanGpsRuleInfoDTO)
                .afsRuleInfoDto(afsRuleInfoDto)
                .afsRuleTransExpress(afsRuleTransExpressList)
                .afsRuleResultMapping(afsRuleResultMapping)
                .afsRuleItem(afsRuleItemList)
                .afsRuleInputMapping(afsRuleInputMappingList)
                .afsRuleExpressAtom(afsRuleExpressAtomList)
                .afsRuleExpress(afsRuleExpressList)
                .build();
        ApproveSubmitInfo approveSubmitInfo = ApproveSubmitInfo.builder()
                .loanGpsRuleDTO(loanGpsRuleDTO)
                .build();
        log.info("-----------------GPS安装规则数据组装end---------------->");

        log.info("-----------------GPS安装规则通知begin---------------->");
        infoSender.sendGpsMsgToApplyNotic(AfsTransEntity.<ApproveSubmitInfo>builder()
                .transCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_MODIFY_ORDER)
                .data(approveSubmitInfo).build());
        log.info("-----------------GPS安装规则通知end---------------->");
    }
    @ApiOperation("放款模式规则数据推送")
    @Override
    public void sendLoanModelToApply(Long id) {
        log.info("-----------------放款模式规则数据组装begin---------------->");

        Assert.isTrue(null != id, "规则【" + id + "】不存在，推送数据失败");

        LoanModeRuleInfo loanModeRuleInfo = loanModeRuleInfoService.getById(id);
        LoanModelRuleInfoDto loanModelRuleInfoDto = new LoanModelRuleInfoDto();
        BeanUtils.copyProperties(loanModeRuleInfo, loanModelRuleInfoDto);

        Long ruleId = loanModeRuleInfo.getRuleId();
        Assert.isTrue(null != ruleId, "规则【" + id + "】规则编号不存在，推送数据失败");

        AfsRuleInfo afsRuleInfo = afsRuleInfoService.getById(ruleId);
        AfsRuleInfoDto afsRuleInfoDto = new AfsRuleInfoDto();
        BeanUtils.copyProperties(afsRuleInfo, afsRuleInfoDto);

        List<AfsRuleTransExpress> afsRuleTransExpressList = afsRuleTransExpressMapper
                .selectList(Wrappers.<AfsRuleTransExpress>lambdaQuery().eq(AfsRuleTransExpress::getRuleId, ruleId));

        AfsRuleResultMapping afsRuleResultMapping = afsRuleResultMappingMapper
                .selectOne(Wrappers.<AfsRuleResultMapping>lambdaQuery().eq(AfsRuleResultMapping::getRuleId, ruleId));

        List<AfsRuleItem> afsRuleItemList = afsRuleItemMapper
                .selectList(Wrappers.<AfsRuleItem>lambdaQuery().eq(AfsRuleItem::getRuleId, ruleId));

        List<AfsRuleInputMapping> afsRuleInputMappingList = afsRuleInputMappingMapper
                .selectList(Wrappers.<AfsRuleInputMapping>lambdaQuery().eq(AfsRuleInputMapping::getRuleId, ruleId));

        List<AfsRuleExpressAtom> afsRuleExpressAtomList = afsRuleExpressAtomMapper
                .selectList(Wrappers.<AfsRuleExpressAtom>lambdaQuery().eq(AfsRuleExpressAtom::getRuleId, ruleId));

        List<AfsRuleExpress> afsRuleExpressList = afsRuleExpressMapper
                .selectList(Wrappers.<AfsRuleExpress>lambdaQuery().eq(AfsRuleExpress::getRuleId, ruleId));
        LoanModelRuleDto loanModelRuleDto = LoanModelRuleDto.builder()
                .loanModelRuleInfoDto(loanModelRuleInfoDto)
                .afsRuleInfoDto(afsRuleInfoDto)
                .afsRuleTransExpress(afsRuleTransExpressList)
                .afsRuleResultMapping(afsRuleResultMapping)
                .afsRuleItem(afsRuleItemList)
                .afsRuleInputMapping(afsRuleInputMappingList)
                .afsRuleExpressAtom(afsRuleExpressAtomList)
                .afsRuleExpress(afsRuleExpressList)
                .build();
        ApproveSubmitInfo approveSubmitInfo = ApproveSubmitInfo.builder()
                .loanModelRuleDto(loanModelRuleDto)
                .build();
        log.info("-----------------放款模式规则数据组装end---------------->");

        log.info("-----------------放款模式规则通知begin---------------->");
        infoSender.sendLoanModelToApplyNotic(AfsTransEntity.<ApproveSubmitInfo>builder()
                .transCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_MODIFY_ORDER)
                .data(approveSubmitInfo).build());
        log.info("----------------放款模式规则通知end---------------->");
    }
}
